<?php include 'header.php'; ?>
            <?php
            include 'db_connect.php';

            if (!isset($_GET['id'])) {
                header("Location: index.php");
                exit();
            }

            $post_id = $_GET['id'];
            $sql = "SELECT * FROM posts WHERE id = $post_id";
            $result = $conn->query($sql);

            if ($result->num_rows == 0) {
                echo '<p>帖子不存在！</p>';
                include 'footer.php';
                exit();
            }

            $post = $result->fetch_assoc();
            ?>

            <article class="post">
                <h2><?php echo $post["title"]; ?></h2>
                <div class="post-meta">作者: <?php echo $post["author"]; ?> | 发布时间: <?php echo $post["created_at"]; ?></div>
                <?php 
                // 检查当前用户是否为作者
                if ($_SESSION['username'] == $post["author"]) {
                    echo '<div class="post-actions">';
                    echo '<a href="edit_post.php?id=' . $post["id"] . '" class="btn">修改文章</a>';
                    echo '<a href="delete_post.php?id=' . $post["id"] . '" class="btn" onclick="return confirm(\'确定要删除这篇文章吗？\')">删除文章</a>';
                    echo '</div>';
                }
                ?>
                <div class="post-content">
                    <?php echo nl2br($post["content"]); ?>
                </div>
            </article>

            <section class="comments">
                <h3>评论区</h3>
                <?php
                $sql = "SELECT * FROM comments WHERE post_id = $post_id ORDER BY created_at ASC";
                $comments_result = $conn->query($sql);

                if ($comments_result->num_rows > 0) {
                    while($comment = $comments_result->fetch_assoc()) {
                        echo '<div class="comment">';
                        echo '<strong>' . $comment["author"] . '</strong> ';
                        echo '<small>' . $comment["created_at"] . '</small>';
                        echo '<p>' . $comment["content"] . '</p>';
                        echo '</div>';
                    }
                } else {
                    echo '<p>暂无评论，快来发表评论吧！</p>';
                }
                ?>

                <div class="add-comment">
                    <h3>添加评论</h3>
                    <form method="post" action="add_comment.php">
                        <input type="hidden" name="post_id" value="<?php echo $post_id; ?>">
                        <label for="content">评论内容：</label>
                        <textarea id="content" name="content" required></textarea>
                        <button type="submit" class="btn">提交评论</button>
                    </form>
                </div>
            </section>
<?php include 'footer.php'; ?>
